<?php

namespace App\Api\Controllers\JiuJiang;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
class PayController extends BaseController{

    //刷卡支付-用户被扫  -1 系统错误 0-其他 1-成功 2-验签失败 3-支付中 4-交易失败
    public function scan_pay($data){
        try {
            $acqSpId = $data['acqSpId'] ?? '';
            $mchtNo = $data['mchtNo'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $total_amount = $data['total_amount'] ?? 0;
            $txnAmt = $total_amount ? $total_amount*100 : 0;
            $authCode = $data['authCode'] ?? '';
            $goodsId = $data['goodsId'] ?? '';
            $goodsInfo = $data['goodsInfo'] ?? '';
            $backUrl = $data['backUrl'] ?? '';
            $merPriv = $data['merPriv'] ?? '';
            $faceFlag = $data['faceFlag'] ?? '';
            $ways_source = $data['ways_source'] ?? '';
            $ledgerAccountFlag = $data['ledgerAccountFlag'] ?? '';
            $goodsTag = $data['goodsTag'] ?? '';
            $subAppId = $data['subAppId'] ?? '';
            $longitude = $data['longitude'] ?? '';
            $latitude = $data['latitude'] ?? '';
            $privateKey = $data['privateKey'] ?? '';
            $private_key = $data['private_key'] ?? '';
            $publicKey = $data['publicKey'] ?? '';
            $termNo = $data['termNo'] ?? '';

            $orderType = '';
            if ($ways_source == 'alipay') { //支付宝
                $orderType = 'alipay';
            } elseif ($ways_source == 'weixin') { //微信支付
                $orderType = 'wechat';
            } elseif ($ways_source == 'unionpay') { //银联二维码
                $orderType = 'unionpay';
            }


            $txnAmt = substr( strval($txnAmt + 1000000000000), 1, 15 ); // 交易金额（分，12 位，不足左补 0）
            $authCode = 'A3' . substr( strval(strlen($authCode) + 1000), 1, 15 ) . $authCode;


            $linkage_data = [
                'requestBranchCode' => '0200000000032', // 请求唯一流水号（固定是：0200000000032）
                'mchtNo' => $mchtNo, // 平台分配的商户号
                'termNo' => $termNo, // 平台分配的终端号
                'secMchtNo' => $mchtNo, // 二级商户号（如无，同商户号）
                'outOrderNo' => $out_trade_no, // 商户订单号（被扫下单时，终端生成的订单号，终端流水唯一流水号）
                'orderName' =>'xiaofei', // 订单名称（管理平台配置商户号后，可反显在消费者支付凭证页面）
                'orderTime' => date('Hms', time()), // 交易时间（例如：HHmmss）
                'orderDate' => date('md', time()), // 交易日期（MMdd）
                'txnAmt' => $txnAmt, // 交易金额（分，12 位，不足左补 0）
                'codeNo' => $authCode, // C2B 条形码信息 格式：A3 + 3 位条形码长度 + 条形码数据
                'ordrNoReturnFlag' => '1', // 返回支付凭证条码
            ];
            $getparams=$this->getSignContent($linkage_data);
            $url='https://pay.jjccb.com/JyPay/pospJson/';
            $obj = new BaseController();
            Log::channel("company")->info(date('Y-m-d H:i:s')."jiujiang-req-".$out_trade_no,[
                "reqDate"=>$linkage_data
                ]);
            try {
                $result = $obj->http_post($url,$getparams,$linkage_data,$private_key);

            }catch (\Exception $e){
                $result="";
                Log::channel("company")->info(date('Y-m-d H:i:s')."jiujiang-error-".$out_trade_no,[
                    "error"=>$e->getMessage().$e->getLine().$e->getFile(),
                ]);
            }
            Log::channel("company")->info(date('Y-m-d H:i:s')."jiujiang-res-".$out_trade_no,[
                "result"=>$result,
            ]);
            $result = json_decode($result, true);
            //file_put_contents('jiujiangq.log',var_export($result,true)."\r\n",FILE_APPEND);

            if($result['code'] == 'A2'){
                return [
                   'status' => '3',
                   'message' => '支付中',
                   'data' => $result['data']
               ];
            }else if($result['code'] == '00'){
                return [
                   'status' => '1',
                   'message' => '支付成功',
                   'data' =>$result['data']
               ];
            }else{
                return [
                   'status' => '2',
                   'message' => '支付失败',
                   'data' =>$result['data']
               ];
            }



        } catch (\Exception $ex) {
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //扫码支付-用户主扫  -1 系统错误 0-其他 1-成功 2-验签失败 3-支付中 4-交易失败
    public function qr_pay($data,$private_key){
        try {
            $acqSpId = $data['acqSpId'] ?? '';
            $acqMerId = $data['acqMerId'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $total_amount = $data['total_amount'] ?? '';
            $txnAmt = $total_amount ? ($total_amount * 100): '';
            $ways_source = $data['ways_source'] ?? '';
            $goodsInfo = $data['goodsInfo'] ?? '';
            $paymentValidTime = $data['paymentValidTime'] ?? '';
            $merPriv = $data['merPriv'] ?? '';
            $longitude = $data['longitude'] ?? '';
            $latitude = $data['latitude'] ?? '';
            $latitude = $data['latitude'] ?? '';
            $notify_url = $data['notify_url'] ?? '';
            $privateKey = $data['privateKey'] ?? '';
            $publicKey = $data['publicKey'] ?? '';
            $mchtNo=$data['mchtNo'] ?? '';

            $orderType = '';
            if ($ways_source == 'alipay') {
                $orderType = 'alipay'; //支付宝
            }
            elseif ($ways_source == 'wechat') {
                $orderType = 'wechat'; //微信支付
            }
            elseif ($ways_source == 'unionpay') {
                $orderType = 'unionpay'; //银联二维码
            }
            elseif ($ways_source == 'mobilepos') {
                $orderType = 'mobilepos'; //手机pos支付
            }
            elseif ($ways_source == 'dycode') {
                $orderType = 'dycode'; //动态立码付(支持当天交易)
            }

            $jiujiang_data = [
                'mchtNo' => $mchtNo, // 商户号
                'signType' => 'RSA', // 固定值RSA
                'outOrderNo' => $out_trade_no, // 订单号
                'orderName' => '11', //订单名称
                'txnAmt' => $total_amount, // 交易金额(单位元)
                'orderDate' => date('Ymd', time()), // 订单日期（例如：20181123）
                'orderTime' => date('His', time()), // 订单时间（例如：114524）
                'qyType' => '0', // 二维码类型(0.动态1.静态)
                'callBackUrl' => $notify_url, // 回调地址url
            ];

            $getparams = $this->getSignContent($jiujiang_data);

            $url = 'https://pay.jjccb.com/JyPay/Gateway/paygateway/dynamic/pay/unifiedOrder';
            $obj = new BaseController();
            $result = $this->http_post($url, $getparams, $jiujiang_data,$private_key);
            $result = json_decode($result, true);

            if ($result['code'] == '200') {
                return [
                    'status' => '1',
                    'message' => '交易成功',
                    'data' => $result['data']
                ];
            }else {
                return [
                    'status' => '0',
                    'message' => '交易失败',
                    'data' => $result['data']
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine(),
            ];
        }
    }


    //查询订单 -1系统错误；0-其他；1-交易成功；2-验签失败；3-转入退款；4-交易结果未明；5-已关闭；6-已撤销(付款码支付)；7-明确支付失败
    public function order_query($data,$private_key){
        try {
            if(isset($data['signType'])){
                $url='https://pay.jjccb.com/JyPay/Gateway/paygateway/dynamic/pay/orderquery';
                $getparams=$this->getSignContent($data);
                $obj = new BaseController();
                $result = $obj->http_post1($url,$getparams,$data,$private_key);
                Log::channel("company")->info("jiujiang-http_post1",[
                    "resDate"=>$result,
                ]);
                //file_put_contents('jiujiangq.log',var_export($result,true)."\r\n",FILE_APPEND);
                $re = json_decode($result, true);
                $re['data']['payNumber']=$re['data']['orderId'];
                if($re['data']['tradState'] == 'PROCESSING'){
                    return [
                       'status' => '1',
                       'message' => '支付中',
                       'pay_status' => '2',
                       'data' => $re['data']
                   ];
                }else if($re['data']['tradState'] == 'SUCCESS'){
                    return [
                       'status' => '1',
                       'pay_status' => '1',
                       'message' => '支付成功',
                       'data' => $re['data']
                   ];
                }else{
                    return [
                       'status' => '1',
                       'pay_status' => '3',
                       'message' => '支付失败',
                       'data' => $re['data']
                   ];
                }
            }else{
                $url='https://pay.jjccb.com/JyPay/pospJson/';
                $getparams=$this->getSignContent($data);
                $obj = new BaseController();
                $result = $obj->http_post1($url,$getparams,$data,$private_key);
                Log::channel("company")->info("jiujiang-http_post1",[
                    "resDate"=>$result,
                ]);
               // file_put_contents('jiujiangq.log',var_export($result,true)."\r\n",FILE_APPEND);
                $re = json_decode($result, true);

                if($re['data']['tradeState'] == '04'){
                    return [
                       'status' => '1',
                       'message' => '支付中',
                       'pay_status' => '2',
                       'data' => $re['data']
                   ];
                }else if($re['data']['tradeState'] == '00'){
                    return [
                       'status' => '1',
                       'pay_status' => '1',
                       'message' => '支付成功',
                       'data' => $re['data']
                   ];
                }else{
                    return [
                       'status' => '1',
                       'pay_status' => '3',
                       'message' => '支付失败',
                       'data' => $re['data']
                   ];
                }
            }
        } catch (\Exception $ex) {
            Log::channel("company")->info("jiujiang-http_post1-error",[
                "resDate"=> $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine(),
            ]);
            return [
                'status' => '-1',
                'pay_status' => '3',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }



    //退款（支持部分退款，支持对90天以内的成功订单） -1系统错误；0-其他；1-成功；2-验签失败；3-失败
    public function refund($data,$private_key){
        try {
            $getparams=$this->getSignContent($data);
            $url='https://pay.jjccb.com/JyPay/pospJson/';
            $obj = new BaseController();
            $result = $obj->http_post1($url,$getparams,$data,$private_key);
            file_put_contents('jiujiangrefund.log',var_export($result,true)."\r\n",FILE_APPEND);
            $re = json_decode($result, true);

            if ($re['code'] == '00') {
                return [
                    'status' => '1',
                    'message' => '退款受理成功',
                    'data' => $re['data']
                ];
            }
            else {
                return [
                    'status' => '-1',
                    'message' => '退款失败成功'
                ];
            }

        } catch (\Exception $ex) {
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //退款查询  -1系统错误；0-其他；1-成功；2-验签失败；3-失败；4-处理中
    public function refund_query($data)
    {
        try {
            $acqSpId = $data['acqSpId'];
            $acqMerId = $data['acqMerId'] ?? '';
            $refund_no = $data['refund_no'] ?? '';
            $privateKey = $data['privateKey'] ?? '';
            $publicKey = $data['publicKey'] ?? '';

            $obj = new BaseController();
            $linkage_data = [
                'acqSpId' => $acqSpId, //代理商编号
                'acqMerId' => $acqMerId, //商户号
                'refund_no' => $refund_no //退款流水号，本次退货交易的订单号
            ];
//            Log::info('联动优势-退款查询');
//            Log::info($linkage_data);
            $re = $obj->http_post($obj->url.$obj->payRefundQuery, $linkage_data, $privateKey, $publicKey);
//            Log::info($re);
            if ($re['status'] == '1') {
                if ($re['data']['respCode'] == '00') {
                    if ($re['data']['origRespCode'] == '00') {
                        return [
                            'status' => '1',
                            'message' => $re['data']['respMsg'] ?? '退款成功',
                            'data' => $re['data']
                        ];
                    }
                    elseif ($re['data']['origRespCode'] == '01') {
                        return [
                            'status' => '3',
                            'message' => $re['data']['respMsg'] ?? '退款失败',
                            'data' => $re['data']
                        ];
                    }
                    elseif ($re['data']['origRespCode'] == '02') {
                        return [
                            'status' => '4',
                            'message' => $re['data']['respMsg'] ?? '退款处理中',
                            'data' => $re['data']
                        ];
                    }
                } else {
                    return [
                        'status' => '0',
                        'message' => $re['data']['respMsg'] ?? '退款状态未知',
                    ];
                }
            }
            elseif ($re['status'] == '2') {
                return [
                    'status' => '2',
                    'message' => '验签失败'
                ];
            }
            else {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }
        } catch (\Exception $ex) {
            Log::info('联动优势-退款查询-错误');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }
}
